<template>
  <div class="balance-page">
    <div class="balance-card">
      <div class="user-info">
        <div class="user-profile">
          <van-image
            round
            width="80"
            height="80"
            :src="userAvatar"
            class="user-avatar"
          />
          <p class="user-nickname">{{ userNickname }}</p>
        </div>
        <div class="balance-info">
          <p class="balance-title">账户余额</p>
          <p class="balance-amount">{{ balance.toFixed(2) }}</p>
        </div>
      </div>
    </div>

    <van-grid :column-num="gridColumnNum" :border="false">
      <van-grid-item icon="balance-pay" text="今日汇总" @click="onTransfer" />
      <van-grid-item icon="balance-list-o" text="收益明细" @click="onViewBill" />
      <van-grid-item 
      v-if="gridColumnNum === 3"
        icon="setting-o" 
        text="设置" 
        @click="onSetting" />
    </van-grid>

    <van-cell-group inset title="在线人员转账">
      <van-cell v-for="person in onlinePersons" :key="person.id">
        <template #icon>
          <van-image
            round
            width="40"
            height="40"
            :src="person.avatar"
          />
        </template>
        <template #title>
          <span class="custom-title">{{ person.name }}</span>
        </template>

        <template #right-icon>
          <div class="transfer-buttons">
            <van-space>
              <span class="transfer-amount" @click="showTransferDialog(person, 5)">5</span>
              <span class="transfer-amount" @click="showTransferDialog(person, 10)">10</span>
              <span class="transfer-amount" @click="showTransferDialog(person, 15)">15</span>
              <span class="transfer-amount" @click="showTransferDialog(person, 20)">20</span>
              <span class="transfer-amount custom" @click="showTransferDialog(person, 0)">其他</span>
            </van-space>
          </div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 添加一个固定在底部的按钮容器 -->
    <div class="bottom-button-container">
      <van-button type="danger" @click="logout" block >退出</van-button>
    </div>
     <!-- 转账对话框 -->
     <van-popup v-model:show="showDialogFlag"  position="bottom" :style="{ height: '60%' }">
      <div class="transfer-dialog">
        <p class="receiver-name">给{{ currentReceiver.name }}转账</p>
        <van-field
          v-model="transferAmount"
          type="text"
          placeholder="请输入金额"
          @click="onMoneyClick"
          class="custom-field"
          readonly
        />
      </div>

      <van-number-keyboard
        v-model="transferAmount"
        :show="showKeyboard"
        theme="custom"
        extra-key="."
        close-button-text="完成"
        @close="confirmTransfer"
        @input="onInput"
        @delete="onDelete"
      />
    </van-popup>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { get , post} from '../../utils/request'; 
import { showToast, showDialog } from 'vant';

export default {
  setup() {
    const router = useRouter();
    const balance = ref(0.00); // 假设初始余额
    const onlinePersons = ref([]);

    const showDialogFlag = ref(false);
    const showKeyboard = ref(false);
    const gridColumnNum = ref(2);
    const transferAmount = ref('');
    const currentReceiver = ref({});
    const userAvatar = ref(''); 
    const userNickname = ref('');

    const onViewBill = () => router.push("/my");
    const onSetting = () => router.push("/setting");
    const onTransfer = () => showToast('今日汇总功能开发中');
 
    const logout = ()=>showDialog({
      title: '确认退出',
      message: '您确定不再玩会吗？',
      showCancelButton: true, 
    }).then(() => {
      localStorage.removeItem('token');
      router.push("/login"); 
    })

    const formatAmount = (amount) => {
      return amount >= 0 ? `+${amount.toFixed(2)}` : amount.toFixed(2);
    };

    const showTransferDialog = (person, amount) => {
      currentReceiver.value = person || {};
      if (amount === 0) {
        showDialogFlag.value = true;
        showKeyboard.value = true;
        transferAmount.value = '';
      } else {
        transferAmount.value = amount;
        confirmTransfer();
      }
    };

    const onInput = (key) => {
      if (transferAmount.value.includes('.') && key === '.') {
        return;
      }
      if (transferAmount.value.split('.')[1]?.length >= 2) {
        return;
      }
      transferAmount.value += key;
    };

    const onMoneyClick = ()=>{
      showKeyboard.value = true;
    }

    const onDelete = () => {
      transferAmount.value = transferAmount.value.slice(0, -1);
    };

    const confirmTransfer = () => {
      if (!transferAmount.value) {
        showToast('请输入转账金额');
        return;
      }

      showDialog({
        title: '确认转账',
        message: `向${currentReceiver.value.name}转账 ${transferAmount.value}（元）`,
        showCancelButton: true,
      }).then(() => {
        // 这里应该调用后端 API 进行实际的转账操作

        transData();
        showDialogFlag.value = false;
        showKeyboard.value = false;
      }).catch(() => {
        // 用户取消操作
      });
    };

    const fetchData = async () => {
      try {
        const response = await get('/point/queryInfo');
        console.log('Response from /point/queryInfo:', response);
        // 根据实际返回的数据结构来更新 balance 和 recentTransactions
        if (response && response.code === 200) {
          balance.value = response.data.balance || 0;
          onlinePersons.value = response.data.onlinePersons || [];
          userAvatar.value = response.data.avatar || '';
          userNickname.value = response.data.username || '';

          const userVersion = response.data.version;
          console.log('User Version:', userVersion);
          if (userVersion === 0) {
            gridColumnNum.value = 3; 
          }
        } 
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    const transData = async () => {
      try {
        const response = await post('/point/trans', {
          toId: currentReceiver.value.id,
          amount: transferAmount.value,
        });
        console.log('Response from /point/trans:', response);
        if (response && response.code === 200) {
          balance.value = response.data || 0;
          showToast('转账成功');

        } 
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    onMounted(() => {
      fetchData();
    });


    return {
      balance,
      onlinePersons,
      gridColumnNum,
      onViewBill,
      onSetting,
      onTransfer,
      formatAmount,
      onMoneyClick,
      showDialogFlag,
      showKeyboard,
      transferAmount,
      currentReceiver,
      showTransferDialog,
      onInput,
      onDelete,
      confirmTransfer,
      transData,
      userAvatar,
      userNickname,
      logout
    };
  },
};
</script>

<style scoped>
.balance-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-top: 15px; /* 添加顶部内边距 */
}

.balance-card {
  background-color: #1989fa;
  color: white;
  padding: 20px;
  margin: 0 15px 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-profile {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 10px;
}

.user-nickname {
  font-size: 16px;
  font-weight: bold;
}

.balance-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

.balance-title {
  font-size: 14px;
  margin-bottom: 2px;
}

.balance-amount {
  font-size: 24px;
  font-weight: bold;
  line-height: -1; 
  margin-top: 5px;
}

.balance-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.van-grid) {
  margin: 0 15px;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
:deep(.van-cell-group) {
  margin: 0 15px 0;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
:deep(.van-cell) {
  align-items: center;
}
:deep(.van-cell__title) {
  display: flex;
  align-items: center;
}
.custom-title {
  margin-left: 10px;
}
:deep(.van-image) {
  margin-right: 10px;
}

.transfer-dialog {
  padding: 20px;
}

:deep(.van-field__control) {
  text-align: right;
}
:deep(.van-field) {
  margin-bottom: 15px;
}
.receiver-name {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #323233; /* Vant 默认文本颜色 */
}

.custom-field :deep(.van-field__value) {
  font-size: 32px;
}

.custom-field :deep(.van-field__placeholder) {
  font-size: 18px;
}

.transfer-amount {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
  padding: 5px 10px;
  cursor: pointer;
  user-select: none;
}

.transfer-amount.custom {
  color: #1989fa;
}

.transfer-amount:active {
  opacity: 0.7;
}

.bottom-button-container {
  position: fixed;
  bottom: 5px;
  left: 12px;
  right: 12px;
}

.bottom-button-container :deep(.van-button) {
  width: 100%;
  height: 40px;
  font-size: 16px;
}
</style>